/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.fieldscope.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Represents a field within a schema.
 * 
 * @author Travis Keep
 */
public class Field {
  
  /**
   * Represents number field type.
   */
  private static final String NUMBER = "Number";
  
  /**
   * Represents string field type.
   */
  private static final String STRING = "String";

  private final String name;
  private final double maximum;
  private final String label;
  private final double minimum;
  private final List<Value> values;
  private final String units;
  private final ValueType type;
  
  /**
   * Name of field. This is to be used as they key parameter in
   * {@link Observation.Builder#putItem}
   */
  public String getName() {
    return name;
  }

  /**
   * Returns true if this field has a maximum value.
   */
  public boolean hasMaximum() {
    return doubleExists(maximum);
  }
  
  /**
   * Maximum value of field. If field has no maximum value, results of calling this
   * are unspecified.
   */
  public double getMaximum() {
    return maximum;
  }
  
  /**
   * Label of field. This is what should be displayed to the user for input.
   */
  public String getLabel() {
    return label;
  }
  
  /**
   * Returns true if this field has a minimum value.
   */
  public boolean hasMinimum() {
    return doubleExists(minimum);
  }
  
  /**
   * Returns minimum value of field. If field has no minimum value, results are unspecified.
   */
  public double getMinimum() {
    return minimum;
  }
  
  /**
   * Returns true if this field has a list of predefined values. If so, this field should be displayed
   * as a combo box to user when fetching input.
   */
  public boolean hasValues() {
    return !values.isEmpty();
  }

  /**
   * Returns valid values for this field. If field has no set of predefined values, returns empty list.
   * Returned list cannot be modified.
   */
  public List<Value> getValues() {
    return values;
  }
  
  /**
   * Returns true if this field has a unit of measurement associated with it.
   */
  public boolean hasUnits() {
    return stringExists(units);
  }

  /**
   * Return unit of measurement associated with this field. If there is no unit of measurement,
   * results are unspecified.
   */
  public String getUnits() {
    return units;
  }
  
  /**
   * Returns the type of field, e.g NUMERIC, STRING.
   */
  public ValueType getType() {
    return type;
  }
  
  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    append("Name", name, builder);
    append("Label", label, builder);
    if (doubleExists(maximum)) {
      appendDouble("Maximum", maximum, builder);
    }
    if (doubleExists(minimum)) {
      appendDouble("Minimum", minimum, builder);
    }
    if (!values.isEmpty()) {
      append("Values", values, builder);
    }
    if (stringExists(units)) {
      append("Units", units, builder);
    }
    append("Type", type, builder);
    return String.format("{%s}", builder);
  }
  
  static List<Field> fromJSON(JSONArray json) throws JSONException {
    List<Field> result = new ArrayList<Field>(json.length());
    for (int i = 0; i < json.length(); i++) {
      result.add(singleFromJSON(json.getJSONObject(i)));
    }
    return result;
  }
  
  private Field(String name, double maximum, String label, double minimum, List<Value> values,
      String units, ValueType type) {
    this.name = name;
    this.maximum = maximum;
    this.label = label;
    this.minimum = minimum;
    this.values = values;
    this.units = units;
    this.type = type;
    
  }
  
  private static void appendDouble(String label, double value, StringBuilder builder) {
    appendComma(builder);
    builder.append(label);
    builder.append('=');
    builder.append(value);
  }

  private static void append(String label, Object value, StringBuilder builder) {
    appendComma(builder);
    builder.append(label);
    builder.append('=');
    builder.append(value);
  }
  
  private static void appendComma(StringBuilder builder) {
    if (builder.length() > 0) {
      builder.append(", ");
    }
  }
  
  private static boolean stringExists(String str) {
    return str != null && str.length() > 0;
  }
  
  private static boolean doubleExists(double d) {
    return !Double.isNaN(d);
  }
  
  private static Field singleFromJSON(JSONObject jsonObject) throws JSONException {
    String name = jsonObject.getString("name");
    double maximum = jsonObject.optDouble("maximum");
    String label = jsonObject.getString("label");
    double minimum = jsonObject.optDouble("minimum");
    JSONArray valuesJSON = jsonObject.optJSONArray("values");
    ValueType type = toValueType(jsonObject.getString("type"));
    List<Value> values;
    if (valuesJSON == null) {
      values = Collections.emptyList();
    } else {
      values = Collections.unmodifiableList(Value.fromJSON(valuesJSON, type));
    }
    String units = jsonObject.optString("units");
    return new Field(
        name, maximum, label, minimum, values, units, type);
  }
  
  private static ValueType toValueType(String type) throws JSONException {
    if (type.equals(NUMBER)) {
      return ValueType.NUMERIC;
    } else if (type.equals(STRING)) {
      return ValueType.STRING;
    } else {
      throw new JSONException("Got unexpected value type: " + type);
    }
  }
}
